//
//  YTValidateIdentityViewController.m
//  YiTuDriverClient
//
//  Created by 石少庸 on 2017/5/22.
//  Copyright © 2017年 Yitu. All rights reserved.
//

#import "YTValidateIdentityViewController.h"
#import "YTPhoneChangeViewController.h"
#import "YTUserLoginAPI.h"

@interface YTValidateIdentityViewController ()
@property (weak, nonatomic) IBOutlet UILabel *tipsText;
@property (weak, nonatomic) IBOutlet UITextField *verifyCodeText;
@property (weak, nonatomic) IBOutlet UIButton *sendVerifyBtn;
@property (weak, nonatomic) IBOutlet UIButton *nextBtn;
@end

@implementation YTValidateIdentityViewController

- (void)initialize {
    _tipsText.text = [NSString stringWithFormat:@"请输入%@收到的短信验证码", [YTUtilityManager manager].userModel.phone];
}

- (void)bindViewModel {
    // 倒计时
    RACSignal *(^counterSignal)(NSNumber *countDown) = ^RACSignal *(NSNumber *countDown) {
        RACSignal *timerSingal = [RACSignal interval:1.0 onScheduler:[RACScheduler mainThreadScheduler]];
        RACSignal *counterSignal = [[timerSingal scanWithStart:countDown reduce:^id(NSNumber *running, id next) {
            return @(running.integerValue - 1);
        }] takeUntilBlock:^BOOL(NSNumber *untilNum) {
            return untilNum.integerValue < 0;
        }];
        
        return counterSignal;
    };
    
    _sendVerifyBtn.rac_command = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
        NSString *phoneNum = [YTUtilityManager manager].userModel.phone;
        NSString *areaCode = [YTUtilityManager manager].userModel.areaCode;
        RACSignal *requestSignal = [YTUserLoginAPI sendVerifyCode:phoneNum areaCode:areaCode];
        return [[RACSignal combineLatest:@[counterSignal(@60), requestSignal]
                                  reduce:^id(NSNumber *countDown, NSDictionary *response){
            if ([response[@"resultCode"] integerValue] == 1001) {
                return @"获取验证码";
            }
            return countDown.integerValue != 0 ? [NSString stringWithFormat:@"(%zd)s后重试", countDown.integerValue] : @"重新发送";
        }] takeUntilBlock:^BOOL(NSString *title) {
            return [title isEqualToString:@"获取验证码"]; // 监测发送短信是否失败了
        }];
    }];
    
    @weakify(self);
    [[_sendVerifyBtn.rac_command.executionSignals switchToLatest] subscribeNext:^(NSString *title) {
        @strongify(self);
        [self.sendVerifyBtn setTitle:title forState:UIControlStateNormal];
    }];
    
    [[self.verifyCodeText.rac_textSignal map:^id(NSString *text) {
        return @(text.length == 6);
    }] subscribeNext:^(NSNumber *enabled) {
        @strongify(self);
        if (enabled.boolValue) {
            [self.view endEditing:YES];
        }
        self.nextBtn.enabled = enabled.boolValue;
        [self.nextBtn setBackgroundColor:enabled.boolValue ? kMainBlueColor : [UIColor lightGrayColor]];
    }];
    
    [[_nextBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        NSString *phoneNum = [YTUtilityManager manager].userModel.phone;
        NSString *areaCode = [YTUtilityManager manager].userModel.areaCode;
        @strongify(self);
        [[YTUserLoginAPI validateVerifyCode:self.verifyCodeText.text phoneNum:phoneNum areaCode:areaCode] subscribeNext:^(id x) {
            [self performSegueWithIdentifier:self.segueIdentifier sender:nil];
        } error:^(NSError *error) {
            self.verifyCodeText.text = @"";
        }];
    }];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"YTChangePhone"]) {
        YTPhoneChangeViewController *phoneChange = segue.destinationViewController;
        phoneChange.oldVerifyCode = self.verifyCodeText.text;
    }
    
    if ([segue.identifier isEqualToString:@"YTSetEmbody"]) {
        YTEmbodyPasswordViewController *embody = segue.destinationViewController;
        embody.type = _type;
        embody.verifyCode = self.verifyCodeText.text;
    }
}

@end
